from django.utils.deprecation import MiddlewareMixin
from user.models import OperationLog
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import AnonymousUser
import re
#黑名单IP
from system_config.models import BlacklistIP
from django.http import HttpResponseForbidden, HttpResponse,JsonResponse
#iddlewareMixin 是一个基类，用于构建中间件（middleware）。
# 中间件是一个轻量级的、底层的“插件”系统，用于在全局范围内修改 Django 的输入或输出。
# 它允许你在视图函数被调用之前或之后执行代码。
class UserOperationLogMiddleware(MiddlewareMixin):

    def process_request(self, request):
        # 在请求处理前记录日志
        # 获取用户，注意这里要处理匿名用户的情况，通过使用token查询用户
        try:
            token = request.META.get('HTTP_AUTHORIZATION', '').split()[1]
            token = Token.objects.get(key=token)
            username = token.user
        except Exception as e:
            token = request.META.get('HTTP_AUTHORIZATION')
            username = None
        url = request.path
        #去除url后面ID
        path = re.sub(r'(\d+/)$', '', url)
        action = request.method
        remote_ip = request.META.get('REMOTE_ADDR')
        #判断如果是匿名用户则不创建操作日志
        if username != None:
            if action == 'PUT':
                action = '修改'
                OperationLog.objects.create(
                    username=username,
                    url=path,
                    action=action,
                    remote_ip=remote_ip
                )
            elif action == 'POST' and '/api/clean_log/' in url:
                action = '删除'
                OperationLog.objects.create(
                    username=username,
                    url=path,
                    action=action,
                    remote_ip=remote_ip
                )
            elif action == 'POST':
                action = '添加'
                OperationLog.objects.create(
                    username=username,
                    url=path,
                    action=action,
                    remote_ip=remote_ip
                )
            elif action == 'DELETE':
                action = '删除'
                OperationLog.objects.create(
                    username=username,
                    url=path,
                    action=action,
                    remote_ip=remote_ip
                )

    def process_response(self, request, response):
        # 在响应返回后也可以记录日志，如果需要的话
        try:
            token = request.META.get('HTTP_AUTHORIZATION', '').split()[1]
            token = Token.objects.get(key=token)
            username = token.user
        except Exception as e:
            username = None
        # 判断如果是匿名用户则不创建操作日志
        if username != None:
            if response.status_code == 200:
                status = 1
            else:
                status = 2
            OperationLog.objects.filter(username=username,url=request.path, action=request.method).update(
                status=status
            )
        return response


class BlacklistMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        ip = request.META.get('REMOTE_ADDR')
        ip_list_obj = BlacklistIP.objects.all()
        ip_list = []
        for i in ip_list_obj:
            if ',' in i.ip_address:
                ip_list.extend(i.ip_address.split(','))
            else:
                ip_list.append(i.ip_address)
        ip_list = list(set(ip_list))  # 列表去重
        if ip in ip_list:
            return HttpResponseForbidden('IP已禁止访问！')
        response = self.get_response(request)
        return response
